package com.lsh.oms.core.service.bills.impl;


import com.alibaba.fastjson.JSON;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.dao.other.OrderSignDetailMapper;
import com.lsh.oms.core.dao.other.OrderSignHeadMapper;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.bills.OrderReceiptVo;
import com.lsh.oms.core.model.order.OrderSignDetail;
import com.lsh.oms.core.model.order.OrderSignHead;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author peter
 * @date 18/11/5
 */
@Service("orderReceiptTmsService")
@Slf4j
public class OrderReceiptKafkaService extends AbstractKafkaMessageService<OrderReceiptVo> {

    @Autowired
    private OrderSignHeadMapper orderSignHeadMapper;

    @Autowired
    private OrderSignDetailMapper orderSignDetailMapper;

    @Override
    public void doBiz(OrderReceiptVo obj) {
        try {
            OrderSignHead head = obj.getOrderReceiptHead();
            List<OrderSignDetail> details = obj.getOrderReceiptDetail();
            OrderSignHead cell = orderSignHeadMapper.selectByReceiptOrderId(head.getReceiptOrderId());
            log.info("签收单 ReceiptOrderId: {} orderSignHead: {}", head.getReceiptOrderId(), JSON.toJSONString(cell));
            if (cell == null) {
                head.setTmsId(head.getId());
                head.setId(null);
                orderSignHeadMapper.insert(head);
                for (OrderSignDetail detail : details) {
                    detail.setTmsId(detail.getId());
                    detail.setId(null);
                    orderSignDetailMapper.insertSelective(detail);
                }
            } else {
                head.setTmsId(head.getId());
                head.setId(null);
                orderSignHeadMapper.updateByTmsId(head);
                for (OrderSignDetail detail : details) {
                    detail.setTmsId(detail.getId());
                    detail.setId(null);
                    orderSignDetailMapper.updateByTmsId(detail);
                }
            }
            log.info("签收单 ReceiptOrderId: {} deal end ", head.getReceiptOrderId());
        } catch (Exception e) {
            log.error("OrderReceiptService ::: Full stack trace follows,:", e);
            throw new BusinessException(ReturnCode.UPDATE_FAIL, "OrderReceiptService db exception", e);
        }
    }

    @Override
    public OrderReceiptVo parse(String json) throws Exception {
        return JSON.parseObject(json, OrderReceiptVo.class);
    }
}
